package com.example.myapplication.ui.record;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import com.example.myapplication.R;
import com.example.myapplication.adapter.CategoryAdapter;
import com.example.myapplication.databinding.FragmentAddRecordBinding;
import com.example.myapplication.data.Record;
import com.example.myapplication.data.RecordRepository;
import com.example.myapplication.model.Category;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.tabs.TabLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class AddRecordFragment extends Fragment {
    private FragmentAddRecordBinding binding;
    private List<Category> expenseCategories;
    private List<Category> incomeCategories;
    private CategoryAdapter categoryAdapter;
    private SimpleDateFormat dateFormat;
    private Calendar calendar;
    private RecordRepository repository;
    private Category selectedCategory;
    private boolean isExpense = true; // 默认为支出
    private Record editingRecord;
    private boolean isEditMode = false;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                            ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentAddRecordBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        repository = new RecordRepository(requireActivity().getApplication());
        
        initCategories();
        setupDatePicker();

        // 检查是否是编辑模式
        if (getArguments() != null) {
            isEditMode = true;
            loadRecordData();
        }

        setupCategoryGrid();
        setupTabLayout();
        setupSaveButton();

        return root;
    }

    private void initCategories() {
        // 初始化支出类别
        expenseCategories = new ArrayList<>();
        expenseCategories.add(new Category(R.drawable.eat, getString(R.string.category_food)));
        expenseCategories.add(new Category(R.drawable.shopping, getString(R.string.category_shopping)));
        expenseCategories.add(new Category(R.drawable.retail, getString(R.string.category_snack)));
        expenseCategories.add(new Category(R.drawable.fruit, getString(R.string.category_fruit)));
        expenseCategories.add(new Category(R.drawable.transport, getString(R.string.category_transport)));
        expenseCategories.add(new Category(R.drawable.car, getString(R.string.category_car)));
        expenseCategories.add(new Category(R.drawable.education, getString(R.string.category_study)));
        expenseCategories.add(new Category(R.drawable.gift, getString(R.string.category_gift)));
        expenseCategories.add(new Category(R.drawable.pet, getString(R.string.category_pet)));
        expenseCategories.add(new Category(R.drawable.game, getString(R.string.category_game)));
        expenseCategories.add(new Category(R.drawable.phone, getString(R.string.category_phone)));
        expenseCategories.add(new Category(R.drawable.lifefee, getString(R.string.category_utility)));
        expenseCategories.add(new Category(R.drawable.sport, getString(R.string.category_sport)));
        expenseCategories.add(new Category(R.drawable.skin, getString(R.string.category_beauty)));
        expenseCategories.add(new Category(R.drawable.other, getString(R.string.category_other_expense)));

        // 初始化收入类别
        incomeCategories = new ArrayList<>();
        incomeCategories.add(new Category(R.drawable.salary, getString(R.string.category_allowance)));
        incomeCategories.add(new Category(R.drawable.vicejob, getString(R.string.category_part_time)));
        incomeCategories.add(new Category(R.drawable.bonus, getString(R.string.category_bonus)));
        incomeCategories.add(new Category(R.drawable.financing, getString(R.string.category_investment)));
        incomeCategories.add(new Category(R.drawable.other, getString(R.string.category_other_income)));
    }

    private void setupCategoryGrid() {
        binding.categoryGrid.setLayoutManager(new GridLayoutManager(requireContext(), 5));
        categoryAdapter = new CategoryAdapter(expenseCategories, (category, position) -> {
            selectedCategory = category;
        });
        binding.categoryGrid.setAdapter(categoryAdapter);
    }

    private void setupTabLayout() {
        binding.typeTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                isExpense = tab.getPosition() == 0;
                Log.d("AddRecordFragment", "Tab selected: " + (isExpense ? "支出" : "收入"));
                selectedCategory = null; // 切换类型时重置选中的类别
                if (isExpense) {
                    categoryAdapter = new CategoryAdapter(expenseCategories, (category, position) -> {
                        selectedCategory = category;
                        Log.d("AddRecordFragment", "Selected expense category: " + category.getName());
                    });
                } else {
                    categoryAdapter = new CategoryAdapter(incomeCategories, (category, position) -> {
                        selectedCategory = category;
                        Log.d("AddRecordFragment", "Selected income category: " + category.getName());
                    });
                }
                binding.categoryGrid.setAdapter(categoryAdapter);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    private void setupDatePicker() {
        // 初始化日期格式化工具
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        calendar = Calendar.getInstance(); // 获取当前日期

        // 设置当前日期作为默认值
        updateDateDisplay();

        // 创建日期选择器
        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择日期")
                .setSelection(calendar.getTimeInMillis())
                .build();

        // 设置日期选择结果监听
        datePicker.addOnPositiveButtonClickListener(selection -> {
            calendar.setTimeInMillis(selection);
            updateDateDisplay();
        });

        // 设置点击事件，显示日期选择器
        binding.datePicker.setOnClickListener(v -> {
            datePicker.show(getParentFragmentManager(), "DATE_PICKER");
        });
    }

    private void updateDateDisplay() {
        binding.datePicker.setText(dateFormat.format(calendar.getTime()));
        Log.d("AddRecordFragment", "Date updated to: " + calendar.getTime());
    }

    private void setupSaveButton() {
        binding.saveButton.setOnClickListener(v -> saveRecord());
    }

    private void loadRecordData() {
        Bundle args = getArguments();
        if (args != null) {
            int recordId = args.getInt("recordId", -1);
            // 只有当 recordId 有效（不为-1）时才是编辑模式
            isEditMode = (recordId != -1);
            
            if (isEditMode) {
                isExpense = args.getBoolean("isExpense", true);
                String category = args.getString("category", "");
                float amount = args.getFloat("amount", 0f);
                long date = args.getLong("date", System.currentTimeMillis());
                String note = args.getString("note", "");

                // 设置支出/收入标签
                binding.typeTabs.selectTab(binding.typeTabs.getTabAt(isExpense ? 0 : 1));

                // 设置类别适配器
                List<Category> categories = isExpense ? expenseCategories : incomeCategories;
                categoryAdapter = new CategoryAdapter(categories, (selectedCategory, position) -> {
                    this.selectedCategory = selectedCategory;
                });
                binding.categoryGrid.setAdapter(categoryAdapter);

                // 查找并选中对应的类别
                for (int i = 0; i < categories.size(); i++) {
                    Category c = categories.get(i);
                    if (c.getName().equals(category)) {
                        selectedCategory = c;
                        categoryAdapter.setSelectedPosition(i);
                        break;
                    }
                }

                // 设置其他UI
                binding.amountEdit.setText(String.format(Locale.getDefault(), "%.2f", (double)amount));
                calendar.setTimeInMillis(date);
                binding.datePicker.setText(dateFormat.format(calendar.getTime()));
                binding.noteEdit.setText(note);

                // 创建编辑中的记录对象
                editingRecord = new Record(isExpense, category, amount, date, note);
                editingRecord.setId(recordId);
            }
        }
    }

    private void saveRecord() {
        // 验证类别是否选择
        if (selectedCategory == null && !isEditMode) {
            Toast.makeText(requireContext(), "请选择类别", Toast.LENGTH_SHORT).show();
            return;
        }

        // 验证金额
        String amountStr = binding.amountEdit.getText().toString().trim();
        if (amountStr.isEmpty()) {
            Toast.makeText(requireContext(), "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            double amount = Double.parseDouble(amountStr);
            if (amount <= 0) {
                Toast.makeText(requireContext(), "金额必须大于0", Toast.LENGTH_SHORT).show();
                return;
            }

            // 使用当前设置的日期
            long recordDate = calendar.getTimeInMillis();
            
            Log.d("AddRecordFragment", "Saving record with date: " + new Date(recordDate));

            if (isEditMode && editingRecord != null) {
                // 更新现有记录
                editingRecord.setExpense(isExpense);
                if (selectedCategory != null) {
                    editingRecord.setCategory(selectedCategory.getName());
                }
                editingRecord.setAmount(amount);
                editingRecord.setDate(recordDate);
                editingRecord.setNote(binding.noteEdit.getText().toString().trim());
                
                Log.d("AddRecordFragment", "Updating record: " + editingRecord);
                repository.update(editingRecord);  // 使用 update 方法更新记录
                Toast.makeText(requireContext(), "记录已更新", Toast.LENGTH_SHORT).show();
            } else {
                // 创建新记录
                Record record = new Record(
                        isExpense,
                        selectedCategory.getName(),
                        amount,
                        recordDate,
                        binding.noteEdit.getText().toString().trim()
                );
                
                Log.d("AddRecordFragment", "Creating new record: " + record);
                repository.insert(record);  // 使用 insert 方法插入新记录
                Toast.makeText(requireContext(), "记录已保存", Toast.LENGTH_SHORT).show();
            }

            requireActivity().onBackPressed();

        } catch (NumberFormatException e) {
            Toast.makeText(requireContext(), "请输入有效的金额", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
} 